//
//  ViewController.m
//  TouchDemo
//
//  Created by 李明明 on 16/1/18.
//  Copyright © 2016年 李明明. All rights reserved.
//

#import "ViewController.h"
#import "LRecordScene.h"
#import "LNetwork.h"
#import "AppleReachability+EX.h"
#import "LTestSceen.h"
#import "LLocation.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<UIViewControllerPreviewingDelegate, CLLocationManagerDelegate>
@property (nonatomic, weak) IBOutlet UIButton * btn;
@property (nonatomic, weak) IBOutlet UIButton *recordBtn;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) void(^location)(NSString *);
@end

@implementation ViewController {
    NSFileManager *fileManager;
    NSString *path;
    NSMutableDictionary *dic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *str = NSLocalizedString(@"testKey", nil);
    NSLog(@"%@", str);
    [self.btn setBackgroundImage:[UIImage imageNamed:@"2"] forState:UIControlStateHighlighted];
//    NSString *str = [AppleReachability stringWithNetWorkStatus];
    NSString *version = [UIDevice currentDevice].systemVersion;
    // 给按钮注册touch事件
    if ([version hasPrefix:@"9"]) {
        [self registerForPreviewingWithDelegate:self sourceView:self.recordBtn];
    }
    fileManager = [NSFileManager defaultManager];
    path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"lmm"];
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    path = [path stringByAppendingPathComponent:@"daka.txt"];
    if (![fileManager fileExistsAtPath:path]) {
        dic = [@{}mutableCopy];
        [fileManager createFileAtPath:path contents:nil attributes:nil];
        [dic writeToFile:path atomically:NO];
    }
    dic = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
    NSLog(@"%@", path);

}
- (void)makeManager {
    self.locationManager = [[CLLocationManager alloc] init];
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        [self.locationManager setDelegate:self];
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 0.1;
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}
- (IBAction)clickBtn:(id)sender {
    [self makeManager];
    [self insertDate:nil];
    BOOL result = [dic writeToFile:path atomically:NO];
    if (result) {
        [self.btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }else {
        [self.btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
}
- (IBAction)lookAtRecord:(id)sender {
    [self performSegueWithIdentifier:@"onetorecord" sender:nil];
}
- (void)copyDic {
    if (![fileManager fileExistsAtPath:path]) {
        dic = [@{}mutableCopy];
        [fileManager createFileAtPath:path contents:nil attributes:nil];
        [dic writeToFile:path atomically:NO];
    }
    dic = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
}
- (NSString *)obtainDate {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}
/** 写入数据
 * location 为定位地址
 */
- (void)insertDate:(NSString * _Nullable)location {
    [self copyDic];
    NSString *dateStr = [self obtainDate];
    NSArray *dates = [dateStr componentsSeparatedByString:@" "];
    if (location != nil) {
        dateStr = [NSString stringWithFormat:@"%@ %@", dateStr, location];
    }
    dic[dates.firstObject] = dateStr;
    [dic writeToFile:path atomically:NO];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"%@", locations);
    CLLocation *location = locations.lastObject;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    LLocation *local = [LLocation singleInstanse];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error == nil && placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks.firstObject;
            NSLog(@"name: %@", placeMark.name);
            NSLog(@"%f", location.altitude);
            [self insertDate:placeMark.name];
            local.coor = location.coordinate;
        }
    }];
    [self.locationManager stopUpdatingLocation];
}
  // 稍微用力按压view时被调用的方法
- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    NSLog(@"hello world");
    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    LRecordScene *recordScene = [stroyboard instantiateViewControllerWithIdentifier:@"recordid"];
    recordScene.dic = dic;
    [recordScene setItem:^(NSNumber* number){
        NSLog(@"%@", number);
    }];
    
    return recordScene;
}
// 大力按压view
- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    [self performSegueWithIdentifier:@"onetorecord" sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.destinationViewController isKindOfClass:[LRecordScene class]]) {
        LRecordScene *recordScene = (LRecordScene *)segue.destinationViewController;
        recordScene.dic = dic;
    }
}
@end
